﻿using MediatR;
using Sgr.Exceptions;
using Sgr.Generator;
using Sgr.UPMS.Domain.Departments;
using Sgr.UPMS.Events;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Domain.Roles
{
    public class RoleManage : IRoleManage
    {
        private readonly IRoleRepository _roleRepository;

        public RoleManage(IRoleRepository repository)
        {
            _roleRepository = repository;
        }

        /// <summary>
        /// 创建一个新的角色 [确保名称唯一]
        /// </summary>
        /// <param name="roleName"></param>
        /// <param name="orgId"></param>
        /// <param name="orderNumber"></param>
        /// <param name="remarks"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="DomainException"></exception>
        public async Task<Role> CreateNewAsync(string roleName, long orgId, int orderNumber, string? remarks, CancellationToken cancellationToken = default)
        {
            Check.StringNotNullOrWhiteSpace(roleName, nameof(roleName));

            if (!await _roleRepository.NameIsUniqueAsync(roleName, null, orgId, cancellationToken))
                throw DomainException.ValidationError("角色名称已存在");

            string code = Guid.NewGuid().ToString("N");
            return new Role(code, roleName, orgId, orderNumber, remarks);
        }

        /// <summary>
        /// 修改角色名称 [确保名称唯一]
        /// </summary>
        /// <param name="role"></param>
        /// <param name="roleName"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task ChangeNameAsync(Role role, string roleName, CancellationToken cancellationToken = default)
        {
            Check.NotNull(role, nameof(role));
            Check.StringNotNullOrWhiteSpace(roleName, nameof(roleName));

            if (!await _roleRepository.NameIsUniqueAsync(roleName, role.Id, role.OrgId, cancellationToken))
                throw DomainException.ValidationError("角色名称已存在");

            role.RoleName = roleName;
        }
    }
}